package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.model.BlowDeviceRepairImage;
import com.jdone.compus.service.RepairImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.nio.file.*;



@RestController
@RequestMapping("/blow/repairs")
@Api(value = "图片上传", tags = "图片")
public class RepairImageController {

    @Autowired
    private  RepairImageService imageService;



    @ApiOperation("通用图片上传（可多文件），返回可访问 URL 列表")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse uploadImages(@RequestPart("files") MultipartFile[] files) {
        try {
            List<BlowDeviceRepairImage> imgs = imageService.storeImages(files);
            // 构造访问 URL，比如前端访问前缀由 Nginx 或静态资源配置决定
            List<String> urls = imgs.stream()
                    .map(img -> "/images/" + img.getRelativePath())
                    .collect(Collectors.toList());
            return ApiResponse.success(urls);
        } catch (IOException e) {
            return ApiResponse.error("上传失败：" + e.getMessage());
        }
    }

    @ApiOperation("根据图片文件名获取完整访问 URL")
    @GetMapping("/images/url")
    public ApiResponse getImageUrl(@RequestParam String name) {
        // name 即相对路径或文件名，如 "2025/07/27/uuid.jpg"
        String url = "/images/" + name;
        return ApiResponse.success(url);
    }

    @ApiOperation("根据相对路径名称获取图片二进制流")
    @GetMapping("/file")
    public ResponseEntity<Resource> serveImage(@RequestParam("name") String name) {
        try {
            RepairImageService.ResourceHolder holder = imageService.loadImage(name);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(holder.getContentType()))
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "inline; filename=\"" + holder.getResource().getFilename() + "\"")
                    .body(holder.getResource());
        } catch (EntityNotFoundException ex) {
            // 找不到就返回 404
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        } catch (Exception ex) {
            // 其他异常返回 500
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}